package org.itzheng.myrxframe.http.retrofit.utils;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Title:文件管理系统<br>
 * Description: <br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2019-3-14.
 */
public class FileManager {
    private static final String TAG = "FileManager";

    /**
     * 目录
     */
    private static class Dir {
        /**
         * app的根目录
         */
        public static final String ROOT = "RxFrame";
        /**
         * 缓存
         */
        public static final String CACHE = "Cache";
        public static final String APK = "Apk";
        /**
         * 崩溃日志
         */
        public static final String CRASH = "Crash";
        /**
         * 普通日志
         */
        public static final String logs = "Logs";
        /**
         * 下载
         */
        public static final String DOWNLOAD = "Download";
    }

    /**
     * APK 备份目录
     *
     * @return
     */
    public static String getApkDir() {
        return new File(getRootFile(), Dir.APK).toString();
    }

    public static String getCacheDir() {
        return new File(getRootFile(), Dir.CACHE).toString();
    }

    /**
     * 获取文件夹根目录，如果有内存卡则是SD卡
     *
     * @return
     */
    public static File getRootFile() {
        if (existSDCard()) {
            return new File(Environment.getExternalStorageDirectory().getAbsolutePath(), Dir.ROOT);
        } else {
            return new File(Environment.getDataDirectory().getAbsolutePath(), Dir.ROOT);
        }
    }

    /**
     * 系统相机位置//手机存储//DCIM//Camera
     *
     * @return
     */
    public static File getCameraDir() {
        String cameraPath = "/DCIM/camera/";
        File cameraDir = null;
        if (existSDCard()) {
            cameraDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), cameraPath);
        } else {
            cameraDir = new File(Environment.getDataDirectory().getAbsolutePath(), cameraPath);
        }
        return cameraDir;
    }

    /**
     * 判断SDCard是否可用
     */
    public static boolean existSDCard() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 获取当前系统时间的时间戳字符串
     *
     * @return 20181231_121359
     */
    public static String getCurrentTimestampStr() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        return dateFormat.format(new Date(System.currentTimeMillis()));
    }

    /**
     * 将bytes保存到指定位置
     *
     * @param bytes
     * @param saveFile
     * @return 是否成功
     */
    public static boolean saveBytesToFile(byte[] bytes, File saveFile) {
        boolean isSuccess = true;
        if (!saveFile.exists()) {
            File dir = new File(saveFile.getParent());
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    //文件创建失败
                    Log.w(TAG, "saveBytesToFile: " + "mkdirs fail!");
                    return false;
                }
            }
            try {
                saveFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(saveFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            isSuccess = false;
        }
        try {
            outStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            isSuccess = false;
        }
        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return isSuccess;
    }

    /**
     * 赋值文件到指定位置
     *
     * @param source  源文件
     * @param dest    目标文件
     * @param isCover 是否覆盖
     * @return
     */
    public static boolean copyFileToFile(File source, File dest, boolean isCover) {
        if (source == null || dest == null) {
            return false;
        }
        if (!source.exists()) {
            new Exception("source 不存在 ").printStackTrace();
            return false;
        }
        if (isCover && dest.exists()) {
            dest.delete();
        } else {
            File parentFile = dest.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
        }
        Log.w(TAG, "copyFileToFile: dest" + dest.getAbsolutePath());
        try {
            dest.createNewFile();
            int bytesum = 0;
            int byteread = 0;
            File oldfile = source;
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldfile); //读入原文件
                FileOutputStream fs = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
